import { _decorator, Collider, Collider2D, Color, Component, Contact2DType, Director, director, EventKeyboard, Input, input, instantiate, KeyCode, macro, Node, Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GamePlay')
export class GamePlay extends Component {
    @property(Node) hensLayout: Node
    @property(Node) player: Node
    @property(Prefab) eggPrefab: Prefab
    @property(Node) eggRoot: Node

    private currentIndex: number = 0

    start() {
        this.initScene()
        this.bindEvent()
    }

    update(deltaTime: number) {
        for (let i = 0; i < this.eggRoot.children.length; i++) {
            const egg = this.eggRoot.children[i]
            const x = egg.worldPosition.x
            const y = egg.worldPosition.y - 100 * deltaTime
            egg.setWorldPosition(x, y, 0)
        }
    }

    initScene() {
        const hens = this.hensLayout.children
        this.player.setPosition(hens[0].position.x, this.player.position.y, 0)
        this.currentIndex = 0

        this.schedule(this.generateEgg, 2, macro.REPEAT_FOREVER, 1)
    }

    generateEgg() {
        const random = Math.floor(Math.random() * 5)
        const pos = this.hensLayout.children[random].worldPosition
        const egg = instantiate(this.eggPrefab)
        this.eggRoot.addChild(egg)
        egg.setWorldPosition(pos)
    }

    bindEvent() {
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this)
        const collider = this.player.getComponent(Collider2D)
        collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
        director.once(Director.EVENT_AFTER_PHYSICS, () => {
            otherCollider.node.destroy()
        })

    }

    onKeyDown(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.KEY_A:
                if (this.currentIndex > 0) this.currentIndex --
                break
            case KeyCode.KEY_D:
                if (this.currentIndex < 4) this.currentIndex ++
                break
        
            default:
                break
        }

        const henPos = this.hensLayout.children[this.currentIndex].position
        // console.log(this.hensLayout.children[this.currentIndex])
        this.player.setPosition(henPos.x, this.player.position.y, 0)
    }

    onDestroy() {
        this.unschedule(this.generateEgg)
    }
}


